﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ThresholdAssistant.ConfigSdk.Extensions
{
    /// <summary>
    /// 安全扩展
    /// </summary>
    public static class SecurityExtensions
    {
        /// <summary>
        /// 密钥
        /// </summary>
        private static readonly string AccessKey = "24T62J8HP64NDRJ4";

        /// <summary>
        /// 有密码的AES加密 
        /// </summary>
        /// <param name="text">需要加密的字符</param>
        /// <returns></returns>
        public static string ToEncrypt(this string text)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(AccessKey);
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(text);
            RijndaelManaged rDel = new RijndaelManaged()
            {
                Key = keyArray,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            cTransform.Dispose();
            return resultArray.Aggregate("", (current, t) => $"{current}{t:x2}");
        }

        /// <summary>
        /// 密钥解析
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ToDecrypt(this string text)
        {
            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return "";
                }

                byte[] keyArray = Encoding.UTF8.GetBytes(AccessKey);
                byte[] toEncryptArray = new byte[text.Length / 2];
                for (int i = 0; i < text.Length; i += 2)
                {
                    toEncryptArray[i / 2] = (byte)Convert.ToInt32(text.Substring(i, 2), 16);
                }
                RijndaelManaged rDel = new RijndaelManaged()
                {
                    Key = keyArray,
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                cTransform.Dispose();
                return Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception)
            {

            }
            return text ?? "";
        }
    }
}